<template>
  <div>
    <!--     搜索条件-->
    <SearchForm @search="getTableData" @reset="clearSearch" :isSearchDisabled="isSearchDisabled">
      <el-col :span="8" :xs="24" v-if="$permiss[109]">
        <el-form-item :label="$t('所属租户')" prop="adminUserId">
          <el-select style="width: 100%" v-model="page.adminUserId" @change="tenantChange" clearable>
            <el-option v-for="item in tenantList" :key="item.adminUserId"
                       :label="item.adminName"
                       :value="item.adminUserId"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('订单编号')" prop="loanRecordId">
          <el-input v-model="page.loanRecordId"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('用户姓名')" prop="name">
          <el-input v-model="page.name"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('手机号码')" prop="phone">
          <el-input v-model="page.phone"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('身份证号码')" label-width="100px">
          <el-input v-model="page.idCard"></el-input>
        </el-form-item>
      </el-col>
      <!--      <el-col :span="8" :xs="24">-->
      <!--        <el-form-item :label="$t('邮箱')">-->
      <!--          <el-input v-model="page.idCard"></el-input>-->
      <!--        </el-form-item>-->
      <!--      </el-col>-->
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('黑猫分')" prop="score">
          <el-row :gutter="24" style="margin: 0">
            <el-col :span="11" style="padding: 0">
              <el-input v-model="page.scoreStart"
                        oninput="value = value.replace(/[^\d]/g, '')"/>
            </el-col>
            <el-col class="line" style="padding: 0;text-align: center;line-height: 32px" :span="2">-</el-col>
            <el-col :span="11" style="padding: 0">
              <el-input v-model="page.scoreEnd"
                        oninput="value = value.replace(/[^\d]/g, '')"/>
            </el-col>
          </el-row>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24" v-show="$permiss[110]">
        <el-form-item :label="$t('订单状态')" prop="approvalResult">
          <el-select style="width: 100%" v-model="page.approvalResult" clearable>
            <el-option v-for="item in userStatusList" :key="item.key" :label="item.value"
                       :value="item.key"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24" v-show="$permiss[108]">
        <el-form-item :label="$t('APP名称')" prop="productName">
          <el-select style="width: 100%" v-model="page.productName" clearable>
            <el-option v-for="item in productList" :key="item.productId"
                       :value="item.productName"
                       :label="item.appName"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('用户状态')" prop="isRepeatedBorrowing">
          <el-select style="width: 100%" v-model="page.isRepeatedBorrowing" clearable>
            <el-option :label="$t('复借')" :value="1"></el-option>
            <el-option :label="$t('初借')" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24" v-show="$permiss[111]">
        <el-form-item :label="$t('信审员')" prop="auditId">
          <el-select style="width: 100%" v-model="page.auditId" clearable>
            <el-option v-for="item in auditList" :key="item.adminUserId" :label="item.adminName"
                       :value="item.adminUserId"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('机审状态')" prop="machine">
          <el-select style="width: 100%" v-model="page.machine" clearable>
            <el-option :label="$t('通过')" :value="0"></el-option>
            <el-option :label="$t('拒绝')" :value="1"></el-option>
            <el-option :label="$t('审核中')" :value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('审核状态')" prop="auditStatus">
          <el-select style="width: 100%" v-model="page.auditStatus" clearable>
            <el-option v-for="item in auditStatusList" :key="item.value" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item label-width="100px" :label="$t('上次审核结果')" prop="upApprovalResult">
          <el-select style="width: 100%" v-model="page.upApprovalResult" clearable>
            <el-option :value="2" :label="$t('通过')"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('是否免审')" prop="avoidAudit">
          <el-select style="width: 100%" v-model="page.avoidAudit" clearable>
            <el-option :label="$t('是')" :value="1"></el-option>
            <el-option :label="$t('否')" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('白名单')" prop="isWhite">
          <el-select style="width: 100%" v-model="page.isWhite" clearable>
            <el-option :label="$t('是')" :value="1"></el-option>
            <el-option :label="$t('否')" :value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('申请时间')" prop="applyTimeValue">
          <el-date-picker
              v-model="page.applyTimeValue"
              style="width: 100%"
              unlink-panels
              value-format="yyyy-MM-dd"
              type="daterange"
              :picker-options="applyPickerOptions"
              range-separator="~"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')">
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('审核时间')" prop="examineTimeValue">
          <el-date-picker
              v-model="page.examineTimeValue"
              style="width: 100%"
              value-format="yyyy-MM-dd"
              unlink-panels
              :picker-options="examinePickerOptions"
              type="daterange"
              range-separator="~"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')">
          </el-date-picker>
        </el-form-item>
      </el-col>
    </SearchForm>


    <el-card style="margin-top: 10px" shadow="never">
      <el-row style="text-align: right;margin: 10px 0">
        <el-button v-show="$permiss[112]" type="primary" @click="visible = true">{{ $t('调单') }}</el-button>
      </el-row>
      <el-row>
        <Table :loading="loading" :table-data="tableData" :table-column="tableColumn" row-key="id" :page="page"
               max-height="600px"
               @handleSizeChange="handleSizeChange"
               @handleCurrentChange="handleCurrentChange">
          <template slot="order" slot-scope="{row}">
            <el-link v-if="$permiss[45]" :underline="false" type="primary" @click="goDetails(row)">{{
                row.loanRecordId
              }}
            </el-link>
            <span v-else>{{ row.loanRecordId }}</span>
          </template>
        </Table>
      </el-row>
    </el-card>
    <Dialog :visible.sync="visible" :title="$t('调单')" :footer="false" @close="transferOrderClose"
            width="90%">
      <TransferOrder ref="transferOrder" :visible="visible" :productList="productList"
                     @confirm="getTableData"></TransferOrder>
    </Dialog>
  </div>
</template>

<script>
import TransferOrder from "./compoents/transferOrder";
import {selectTenant, selectProduct, selectAuditStaff} from "@/api/system";
import {fetchAllOrderList} from '@/api/order'
import {defaultTimeDate, dateFormatSection} from "@/utils/tools";
import eventBus from "@/utils/eventBus";
import {encrypt} from "@/utils/encrypt"

export default {
  name: 'orderAll',
  data() {
    return {
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        applyTimeValue: defaultTimeDate(7)
      },
      applySelectDate: null,
      applyPickerOptions: {
        onPick: ({maxDate, minDate}) => {
          this.applySelectDate = minDate.getTime()
          if (maxDate) {
            this.applySelectDate = null
          }
        },
        disabledDate: (time) => {
          // 最大可以选择前后31天时间
          if (this.applySelectDate !== null) {
            const dayNum = 30 * (24 * 60 * 60 * 1000)
            const minTime = this.applySelectDate - dayNum
            const maxTime = this.applySelectDate + dayNum
            return time.getTime() < minTime || time.getTime() > maxTime
          }
        }
      },
      examineSelectDate: null,
      examinePickerOptions: {
        onPick: ({maxDate, minDate}) => {
          this.examineSelectDate = minDate.getTime()
          if (maxDate) {
            this.examineSelectDate = null
          }
        },
        disabledDate: (time) => {
          // 最大可以选择前后31天时间
          if (this.examineSelectDate !== null) {
            const dayNum = 30 * (24 * 60 * 60 * 1000)
            const minTime = this.examineSelectDate - dayNum
            const maxTime = this.examineSelectDate + dayNum
            return time.getTime() < minTime || time.getTime() > maxTime
          }
        }
      },
      visible: false,
      auditList: [],
      userStatusList: [
        {key: -1, value: this.$t('已关闭'), color: '#5e5e5e'},
        {key: 0, value: this.$t("未分配"), color: '#1200ff'},
        {key: 1, value: this.$t("审核中"), color: "#5e5e5e"},
        {key: 2, value: this.$t("拒绝"), color: "#9c0000"},
        {key: 5, value: this.$t("待打款"), color: "#009200"},
        {key: 6, value: this.$t("待还款"), color: "#ffc000"},
        {key: 8, value: this.$t("逾期"), color: "#ff0000"},
        {key: 9, value: this.$t("结清"), color: "#5e5e5e"},
      ],
      productList: [],
      tenantList: [],
      tableColumn: [
        {label: this.$t('订单编号'), slot: 'order', align: 'center', fixed: 'left', minWidth: 200},
        {label: this.$t('用户姓名'), prop: 'name', align: 'center', width: 120},
        {label: this.$t('手机号码'), prop: 'phone', align: 'center', width: 100,},
        {label: this.$t('身份证号码'), prop: 'idcard', align: 'center', width: 120},
        {label: this.$t('白名单'), prop: 'isWhite', align: 'center'},
        {label: this.$t('申请时间'), prop: 'loanTime', align: 'center', width: 150},
        {label: this.$t('黑猫分'), prop: 'score', align: 'center', width: 100},
        {label: this.$t('申请金额'), prop: 'loanAmount', align: 'center'},
        {label: this.$t('借款周期'), prop: 'loanTerm', align: 'center'},
        {label: this.$t('结清次数'), prop: 'settleNumber', align: 'center',},
        {label: this.$t('机审状态'), prop: 'machine', align: 'center', isHtml: true},
        {label: this.$t('上次审核结果'), prop: 'upApprovalResult', align: 'center', width: 100},
        {label: this.$t('审核状态'), prop: 'auditStatus', align: 'center',},
        {label: this.$t('订单状态'), prop: 'approvalResult', align: 'center', component: 'OrderStatus'},
        {label: this.$t('合同金额'), prop: 'passAmount', align: 'center'},
        {label: this.$t('信审员'), prop: 'auditName', align: 'center', width: 120},
        {label: this.$t('审核时间'), prop: 'approvalTime', align: 'center', width: 150},
        {label: this.$t('APP名称'), prop: 'appName', align: 'center'},
        {label: this.$t('是否免审'), prop: 'avoidAudit', align: 'center'},
        {label: this.$t('所属租户'), prop: 'adminUserName', align: 'center', width: 120, isHide: !this.$permiss[109]},
        // {
        //   label: this.$t('操作'),
        //   slot: 'handle',
        //   align: 'center',
        //   minWidth: 150,
        //   isHide: !this.$permiss[717],
        //   fixed: 'right'
        // },
      ],
      tableData: [],
      auditStatusList: [
        {label: this.$t('初审审核中'), value: 0},
        {label: this.$t('初审拒绝'), value: 1},
        {label: this.$t('初审通过'), value: 2},
        {label: this.$t('初审关闭'), value: 3},
        {label: this.$t('终审审核中'), value: 4},
        {label: this.$t('终审拒绝'), value: 5},
        {label: this.$t('终审通过'), value: 6},
        {label: this.$t('终审关闭'), value: 7},
      ],
      loading: false,
      isSearchDisabled: false
    }
  },
  mounted() {
    this.getTableData()
    this.getSelectData()
    // 监听审核成功事件
    eventBus.$on('examineSuccess', this.getTableData)
  },
  components: {
    TransferOrder
  },
  methods: {
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getTableData()
    },
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.getTableData()
    },
    async getTableData() {
      const {isWhite, avoidAudit, applyTimeValue, examineTimeValue} = this.page
      if (isWhite || (avoidAudit || avoidAudit === 0)) {
        if (!applyTimeValue && !examineTimeValue) {
          return this.$message.error(this.$t('按白名单、是否免审查询时,必须选择时间查询条件'))
        }
      }
      const [loanDatetimeStart, loanDatetimeEnd] = dateFormatSection(this.page.applyTimeValue)
      const [datetimeStart, datetimeEnd] = dateFormatSection(this.page.examineTimeValue)
      const params = {
        loanDatetimeStart, loanDatetimeEnd,
        datetimeStart, datetimeEnd,
        ...this.page
      }
      // 删除日期属性
      delete params.examineTimeValue
      delete params.applyTimeValue
      this.loading = true
      this.isSearchDisabled = true
      const res = await fetchAllOrderList(params)
      if (res.code === 1) {
        const {list, total} = res.data
        const machineStatus = (value, color) => {
          return `<span class="highlight" style="color: ${color}">${value}</span>`
        }
        this.tableData = list.map(item => {
          item.avoidAudit = item.avoidAudit === 1 ? this.$t('是') : this.$t('否')
          item.machine = item.machine === 0 ? machineStatus(this.$t('通过'), '#4ce308') : item.machine === 1 ? machineStatus(this.$t('拒绝'), '#f51458') : machineStatus(this.$t('审核中'))
          item.auditStatus = item.auditName ? this.formaterAuditStatus(item) : ''
          item.upApprovalResult = item.upApprovalResult === 2 ? this.$t('通过') : ''
          item.isWhite = item.isWhite === 1 ? this.$t('是') : item.isWhite === 2 ? this.$t('否') : ''
          return item
        })
        this.page.total = total
        this.loading = false
        this.isSearchDisabled = false
      } else {
        this.loading = false
        this.isSearchDisabled = false
      }
    },

    tenantChange(value) {
      selectProduct({adminUserId: value}).then(res => {
        this.productList = res.data
        this.$set(this.page, 'productName', null)
      })
    },
    async getSelectData() {
      selectAuditStaff().then(res => {
        this.auditList = res.data
      })
      selectProduct().then(res => {
        this.productList = res.data
      })
      selectTenant().then(res => {
        this.tenantList = res.data
      })
    },

    goDetails(row) {
      const query = {
        userStubId: row.userStubId,
        userId: row.userId,
        approvalId: row.approvalId,
        orderId: row.loanRecordId,
        permissId: 45,
        productName: row.productName
      }
      this.$router.push({
        path: `/order/orderDetails`,
        query: {
          params: encrypt(query)
        }
      })
    },
    formaterAuditStatus(item) {
      let status = ''
      let type = ''
      const {auditStatus, approvalType} = item
      const statusObj = {
        0: this.$t('审核中'),
        1: this.$t('拒绝'),
        2: this.$t('通过'),
        3: this.$t('关闭')
      }
      type = approvalType === 1 ? this.$t('初审') : approvalType === 2 ? this.$t('终审') : ''
      status = statusObj[auditStatus] ? statusObj[auditStatus] : ''
      return type + status
    },
    transferOrderClose() {
      this.$refs.transferOrder.tableData = []
      this.$refs.transferOrder.clearForm()
    },
    clearSearch() {
      this.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      }
      this.getTableData()
    },

  },
  beforeDestroy() {
    eventBus.$off('examineSuccess', this.getTableData)
  },
}
</script>

<style scoped>

</style>
